package cn.kgc.crowd1040.fundingadmin.controller;


import cn.kgc.crowd1040.fundingadmin.common.CrowdFundingConstant;
import cn.kgc.crowd1040.fundingadmin.common.CrowdFundingUtils;
import cn.kgc.crowd1040.fundingadmin.pojo.Admin;
import cn.kgc.crowd1040.fundingadmin.service.AdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gl
 * @since 2022-10-21
 */
@Controller
public class AdminController {
    @Resource
    AdminService adminService;

    @GetMapping("/admin/to/login/page.html")
    public String toLogin(){
        return "admin/admin-login";
    }

    //验证登录
    @PostMapping("/admin/do/login")
    public String doLogin( @RequestParam("loginAcct") String loginAcct,
                           @RequestParam("userPswd") String userPswd,
                           Model model,
                           HttpSession session){
        //明文转秘闻
        String md5 = CrowdFundingUtils.md5(userPswd);
        //根据用户名和密码查用户
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("login_acct",loginAcct);
        queryWrapper.eq("user_pswd",md5);
        Admin admin = adminService.getOne(queryWrapper);
        //用户为null跳转登录页，显示错误信息
        if (admin==null){
            model.addAttribute(CrowdFundingConstant.ATTR_NAME_MESSAGE, CrowdFundingConstant.MESSAGE_LOGIN_FAILED);
            return "admin/admin-login.html";
        }
        //用户不为null，保存session，跳转后台首页
        session.setAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_ADMIN, admin);
        return "redirect:/admin/to/main/page.html";
    }

    @GetMapping("/admin/to/main/page.html")
    public String toMainPage(){
        return "admin/admin-main";
    }

    //退出登录
    @RequestMapping("/admin/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index";
    }

    //全局异常处理
    @ExceptionHandler(value=Exception.class)
    public String catchException(Exception exception, Model model){
        model.addAttribute(CrowdFundingConstant.ATTR_NAME_ERROR_MESSAGE, exception.getMessage());
        return "system-error";
    }

    //分页
    @RequestMapping("/admin/query/for/search")
    public String queryForSearch(
            // 如果页面上没有提供对应的请求参数，那么可以使用defaultValue指定默认值
            @RequestParam(value="pageNum", defaultValue="1") Integer pageNum,
            @RequestParam(value="pageSize", defaultValue="5") Integer pageSize,
            @RequestParam(value="keyword", defaultValue="") String keyword,
            Model model) {
        Page<Admin> page=new Page<>(pageNum, pageSize);
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("login_acct",keyword).or().like("user_name", keyword).or().like("email", keyword);
        adminService.page(page, queryWrapper);
        model.addAttribute("total",page.getTotal());
        model.addAttribute("pageSize",page.getSize());
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("list",page.getRecords());
        return "admin/admin-page";
    }

    //批量删除
    @ResponseBody
    @PostMapping("/admin/batch/remove")
    public R batchRemove(@RequestBody List<Integer> adminIdList) {
        adminService.removeByIds(adminIdList);
        return R.ok(null);
    }

    //新增
    @GetMapping("/admin/to/add/page.html")
    public String toAdd(){
        return "admin/admin-add";
    }

    /**
     * 添加用户
     * @param admin
     * @return
     */
    @RequestMapping("/admin/save")
    public String saveAdmin(Admin admin) {
        String userPswd=admin.getUserPswd();
        userPswd=CrowdFundingUtils.md5(userPswd);
        admin.setUserPswd(userPswd);
        adminService.save(admin);
        return "redirect:/admin/query/for/search";
    }

    //修改
    @GetMapping("/admin/to/edit/page")
    public String toUpdate(Integer adminId, Integer pageNum, Model model){
        Admin admin = adminService.getById(adminId);
        model.addAttribute("ADMIN", admin);
        return "admin/admin-edit";
    }

    /**
     * 修改
     */
    @RequestMapping("/admin/update")
    public String updateAdmin(Admin admin,Integer pageNum) {
        try {
            if (CrowdFundingUtils.stringEffective(admin.getUserPswd())){
                String userPswd=admin.getUserPswd();
                userPswd=CrowdFundingUtils.md5(userPswd);
                admin.setUserPswd(userPswd);
            }
            adminService.updateById(admin);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/admin/query/for/search?pageNum="+pageNum;
    }
}

